import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:C20Driver/utils/encrypt_data.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:C20Driver/config/service_api.dart';
import 'package:C20Driver/database/advert_picture_base.dart';
import 'package:C20Driver/event/event_bus.dart';
import 'package:C20Driver/model/error_entity.dart';
import 'package:C20Driver/model/getDriverInfo.dart';
import 'package:C20Driver/model/get_driver_statistics_date.dart';
import 'package:C20Driver/model/get_share_info_model.dart';
import 'package:C20Driver/model/get_trip_order_info.dart';
import 'package:C20Driver/model/geyMyCarInfo.dart';
import 'package:C20Driver/model/model.dart';
import 'package:C20Driver/model/release_schedule_model.dart';
import 'package:C20Driver/provider/driver_information.dart';
import 'package:C20Driver/provider/order_information.dart';
import 'package:C20Driver/provider/position_information.dart';
import 'package:C20Driver/resources/app_storage_interface.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/utils/MyDialog.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'mqtt_manage.dart';
import 'service_method.dart';

// class Request extends DriverInformation {
class Request {
  /// 发送验证码
  static sendVerificationCode(
      BuildContext context, String cellPhoneNumber) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.sendSms, params: {
      'mobile': cellPhoneNumber,
      'type': '0010',
    }, success: (res) async {
      ToastX.center('获取验证码成功');
    }, failed: (err) {
      ToastX.center('获取验证码失败');
    });
  }

  /// 验证码登陆
  static void codeLogin(
      BuildContext context, String mobile, String verificationCode) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.codeLogin,
        params: {'mobile': mobile, 'code': verificationCode},
        success: (res) async {
      Navigator.pop(context);
      if (res == null) return;
      // 修改登录状态
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString(
          AppStorageInterface.LOGINTOKEN, res['data']); // 存储token到本地
      NavigatorUtil.goToHomeRemovePage(context);
    }, failed: (err) {
      Navigator.pop(context);
    });
  }

  /// 获取车主当日数据
  static Future<GetDriverStatisticsDate> getDriverStatisticsFun(
      BuildContext context) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.getDriverStatisticsDate, params: {},
            success: (res) async {
      return GetDriverStatisticsDate.fromJson(res);
    });
  }

  /// 首次打开获取司机信息
  static Future<GetDriverInfo> getDriverInfoFun(BuildContext context) async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.getDriverInfo,
        params: {}, success: (res) async {

          var data= await EncryptData.decryptHttpData(res);
           print('qqqqqqq----$data');
      Provider.of<DriverInformation>(context, listen: false).setDriverJson(data);
      var getDriverInfoData = GetDriverInfo.fromJson(data);
      Provider.of<DriverInformation>(context, listen: false)
          .setDriverInformation(
              authenticationStatus: getDriverInfoData.authenticationStatus,
              driverName: getDriverInfoData.driverName,
              headimgurl: getDriverInfoData.headimgurl,
              userId: getDriverInfoData.userId,
              workingStatus: getDriverInfoData.receiptState,
              driverPhone: getDriverInfoData.driverPhone,
              idNo: getDriverInfoData.idNo);
      // SocketManage().initWebSocket(context, getDriverInfoData.userId);
      // MqttManage.getInstance().init(getDriverInfoData.userId, context);
      // Jpush().setJpushAlias('driver_123123');
          var _state =await getBoolValue(AppStorageInterface.UPLOADVERSION) ;
          SharedPreferences prefs = await SharedPreferences.getInstance();
          var localVersion=prefs.getString(AppStorageInterface.VERSION);
          PackageInfo packageInfo = await PackageInfo.fromPlatform();
          String version=packageInfo.version;
          print("3333333qqq  $_state"  );
          print("3333333qqq  $version"  );
          print("3333333qqq  $localVersion");
          if(!_state||localVersion!=version){
            submitMobileInfo(version);
          }
      return getDriverInfoData;
    });
  }
  static Future<bool> getBoolValue(String key, [bool defaultValue = false]) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool(key) ?? defaultValue;
  }
  static Future submitMobileInfo(String version) async{
    String platform = Platform.isAndroid?"android":"ios";

    await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getAppVersion,
      params: {
        'appType': "driver",
        'mobileBrand': "brand",
        "appVersion":version,
        "mobileType":platform
      },
      success: (data) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setBool(AppStorageInterface.UPLOADVERSION,true);
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        String version = packageInfo.version;
        prefs.setString(AppStorageInterface.VERSION, version);
      },
    );
  }
  /// 首次打开获取司机信息
  static Future<GetDriverInfo> getDriverInfo(BuildContext context) async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.getDriverInfo,
        params: {}, success: (res) async {
      // print('qqqqqqq----$res');
      var getDriverInfoData = GetDriverInfo.fromJson(res);
      // SocketManage().initWebSocket(context, getDriverInfoData.userId);
      // MqttManage.getInstance().init(getDriverInfoData.userId, context);
      // Jpush().setJpushAlias('driver_123123');
      return getDriverInfoData;
    });
  }

  /// 获取并设置司机信息
  static void getSetDriverInfo(BuildContext context) async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.getDriverInfo,
        params: {}, success: (res) async {
      var getDriverInfoData = GetDriverInfo.fromJson(res);
      Provider.of<DriverInformation>(context, listen: false)
          .setDriverInformation(
        userId: getDriverInfoData.userId,
        // ID
        driverName: getDriverInfoData.driverName,
        // 司机姓名
        headimgurl: getDriverInfoData.headimgurl,
        // 头像
        driverPhone: getDriverInfoData.driverPhone,
        // 手机号
        authenticationStatus: getDriverInfoData.authenticationStatus,
        // 车主认证状态
        idNo: getDriverInfoData.idNo,
        // 身份证号
        workingStatus: getDriverInfoData.receiptState, // 出车状态
      );
    });
  }

  // 获取并设置车辆信息
  static void geyMyCarInfo(BuildContext context) async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getDriverCertificates,
      params: {},
      success: (res) async {
        var geyMyCarDataInfo = GeyMyCarInfo.fromJson(res);
        Provider.of<DriverInformation>(context, listen: false)
            .setDriverInformation(
          vehicleNumberPlate: geyMyCarDataInfo.vehicleInfo.vehicleNo,
          // 车牌信息
          carAddress: geyMyCarDataInfo.driverInfo.address,
          // 车辆城市
          brandModels: geyMyCarDataInfo.vehicleInfo.model,
          // 车辆品牌信息
          vehicleColor: geyMyCarDataInfo.vehicleInfo.vehicleColor,
          // 车辆颜色
          vin: geyMyCarDataInfo.vehicleInfo.vin,
          // 车辆识别码
          engineid: geyMyCarDataInfo.vehicleInfo.engineid,
          // 发动机号
          distance: geyMyCarDataInfo.vehicleInfo.distance,
          // 行驶里程
          certifyDate: geyMyCarDataInfo.vehicleInfo.certifyDateA,
          // 上牌时间
          frontDriverLicense: geyMyCarDataInfo.driverInfo.licenseFront,
          // 驾驶证正面
          backDriverLicense: geyMyCarDataInfo.driverInfo.licenseBack,
          // 驾驶证背面
          frontDrivingLicense: geyMyCarDataInfo.vehicleInfo.driverLicenseFront,
          // 行驶证正面
          backDrivingLicense: geyMyCarDataInfo.vehicleInfo.driverLicenseBack,
          // 行驶证背面
          frontIdCard: geyMyCarDataInfo.driverInfo.iDFront,
          // 身份证正面
          backIdCard: geyMyCarDataInfo.driverInfo.iDBack,
          // 身份证背面
          dateTimeCertification:
              geyMyCarDataInfo.driverInfo.getdriverLicenseDate,
          // 驾驶证初领证日期
          termValidity: geyMyCarDataInfo.driverInfo.driverLicenseOff,
          // 驾驶证有效期
          carImageList: geyMyCarDataInfo.vehicleInfo.carImg,
          // 车辆照片
          employment: geyMyCarDataInfo.driverInfo.employment,
          // 网约车驾驶证照片
          operate: geyMyCarDataInfo.driverInfo.operate,
          // 车辆运行证
        );
        return geyMyCarDataInfo;
      },
    );
  }

  /// 上传图片
  static Future uploadImg(String path) async {
    print('uploadImguploadImguploadImguploadImg$path');
    return await DioUtils().uploadFile(
      ReqMethod.POST,
      ServiceApi.uploadImg,
      params: {'file': path},
      success: (res) async {
        ToastX.center('图片上传成功');
        return res;
      },
    );
  }

  /// 上传图片
  static Future uploadHeadImg(String path) async {
    return await DioUtils().uploadFile(ReqMethod.POST, ServiceApi.uploadHeadImg,
        params: {'file': path}, success: (res) async {
      ToastX.center('图片上传成功');
      return res;
    });
  }

  /// 头像修改
  static Future modifyHeadImg(String path) async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.modifyHeadImg,
        params: {'headimgurl': path}, success: (res) async {
      ToastX.center('头像修改成功');

      return res;
    });
  }

  /// 上传反馈内容
  static Future submitInput(
      String choice, List<String> selected, String opinionString) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.submitFeeback, params: {
      'basic_info': choice,
      'content': opinionString,
      'img': selected,
    }, success: (res) async {
      ToastX.center('反馈成功');
      return res;
    });
  }

  /// 获取每日收益
  static Future getDriverDailyIncome(String numRecordTime) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.driverDailyIncome, params: {
      'date': numRecordTime,
    }, success: (res) async {
      print("--------->$res");
      return res;
    });
  }

  /// 每日流水
  static Future getIncomeByDay(String days) async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getIncomeByDay,
      params: {'days': days},
      success: (res) async {
        print("--------->$res");
        return res;
      },
    );
  }

  /// 获取顺风车同行乘客
  static Future getFreeRidePeerOrdersFun(String id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.getFreeRidePeerOrders,
        params: {'order_id': id}, success: (res) async {
      return res;
    });
  }

  /// 司机拒绝顺风车订单
  static Future refuseFreeRideOrder(BuildContext context, Map info) async {
    await DioUtils()
        .request(ReqMethod.POST, ServiceApi.refuseFreeRideOrder, params: {
      'id': info['id'],
      'order_id': info['order_id'],
    }, success: (res) async {
      eventBus.fire(new RefreshCarpoolPassengers(1));
      ToastX.center('取消成功');
    });
  }

  /// 获取顺风车订单详情信息
  static Future getFreeRideOrderDataFun(id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.getFreeRideOrderData,
        params: {'order_id': id}, success: (res) async {
      return res;
    });
  }

  /// 司机获取乘客顺风车列表
  static Future getLookingPassengersFun(String id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.getUserRideOrderList,
        params: {'ride_id': id, 'page': '1', 'pageSize': '100'},
        success: (res) async {
      print('000000000=======' + res);
      return res;
    });
  }

  /// 获取首页进行中顺风车订单
  static Future getFreeRideOrderList() async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.driverGetOnTripFreeRide,
      params: {},
      success: (res) async {
        print('0000000000000');
        if (res.length == 0) {
          return {};
        } else {
          return res;
        }
      },
    );
  }

  /// 取消该顺风车行程
  static Future<bool> cancelFreeRideOrder(
      {BuildContext context, String id}) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.cancelFreeRideOrder,
        params: {'order_id': id}, success: (res) async {
      ToastX.center('取消成功');
      eventBus.fire(new CancelCarpoolOrderMark());

      /// 首页获取有无进行中顺风车订单
      eventBus.fire(new OrderWindmillTravel());
      return true;
    });
  }

  /// 发布顺风车行程
  static Future<bool> sendReleaseSchedule(BuildContext context) async {
    OrderInformation provider =
        Provider.of<OrderInformation>(context, listen: false);
    if (provider.windmillStartingPoint == '请输入起点名称')
      return ToastX.center('请选择出发位置');
    if (provider.endOfWindmill == '你想要去哪儿？') return ToastX.center('请选择到达位置');
    if (provider.seatNum == '' || provider.seatNum.length < 1)
      return ToastX.center('请选择座位数');
    ReleaseScheduleModel data = ReleaseScheduleModel.fromJson({
      "departure_date": provider.departureTimeTransmission.toString(), // 出发日期
      'dep_city': provider.startingPointDowntownArea, // 出发城市
      'dep_longitude':
          provider.windmillStartingPointLocation['lng'].toString(), // 预计出发地点经度
      'dep_latitude':
          provider.windmillStartingPointLocation['lat'].toString(), // 预计出发地点纬度
      'dep_are': provider.windmillStartingPoint, // 出发地点
      'dest_city': provider.terminalUrbanArea, // 终点城市
      'dest_area': provider.endOfWindmill, // 下车点
      'dest_longitude':
          provider.endOfWindmillLocation['lng'].toString(), // 预计到达地点经度
      'dest_latitude':
          provider.endOfWindmillLocation['lat'].toString(), // 预计到达地点纬度
      'seat_num': provider.seatNum.toString(), // 座位数
      'order_type': '0010' // 下单类型,订单类型 0010司机下单 0020乘客下单
    });
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.freeRidePlaceOrder,
      params: {
        'departure_date': data.departureDate, // 出发日期
        'dep_city': data.depCity, // 出发城市
        'dep_longitude': data.depLongitude, // 预计出发地点经度
        'dep_latitude': data.depLatitude, // 预计出发地点纬度
        'dep_are': data.depAre, // 出发地点
        'dest_city': data.destCity, // 终点城市
        'dest_area': data.destArea, // 下车点
        'dest_longitude': data.destLongitude, // 预计到达地点经度
        'dest_latitude': data.destLatitude, // 预计到达地点纬度
        'seat_num': data.seatNum, // 座位数
        'order_type': '0010', // 下单类型,订单类型 0010司机下单 0020乘客下单
      },
      success: (res) async {
        // provider.cleanCarpoolLocalInfo();
        /// 首页获取有无进行中顺风车订单
        eventBus.fire(new OrderWindmillTravel());
        NavigatorUtil.jump(
                context, '/generateWindmillTrip?id=${res["id"]}&start=0000')
            .then((res) {});
        return true;
      },
    );
  }

  /// 司机获取乘客顺风车详情
  static Future getUserRideOrderInfo(String id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.getUserRideOrderInfo,
        params: {'ride_id': id}, success: (res) async {
      return res;
    });
  }

  /// 司机接到某个顺风车乘客
  static void receivePassenger(BuildContext context, String id) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.receivePassenger,
        params: {'order_id': id}, success: (res) async {
      Navigator.pop(context);
      eventBus.fire(new RefreshCarpoolPassengers(1));
      eventBus.fire(new SetHitchRichProgress(1));
    });
  }

  /// 司机顺风车完成
  static Future<bool> orderFulfillment(BuildContext context, String id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.driverCompleteFreeRideOrder,
        params: {'order_id': id}, success: (res) async {
      eventBus.fire(new RefreshCarpoolPassengers(2));
      eventBus.fire(new OrderWindmillTravel());
      eventBus.fire(new CancelCarpoolOrderMark());
      return true;
    });
  }

  /// 提交身份证与驾驶证信息到后台
  static Future<void> submitCertificatesInfo(BuildContext context) async {
    DriverInformation provider =
        Provider.of<DriverInformation>(context, listen: false);
    if (provider.driverInfo.frontIdCard == null)
      return ToastX.center('请上传身份证正面');
    if (provider.driverInfo.backIdCard == null)
      return ToastX.center('请上传身份证背面');
    if (provider.driverInfo.frontDriverLicense == null)
      return ToastX.center('请上传驾驶证正面');
    if (provider.driverInfo.backDriverLicense == null)
      return ToastX.center('请上传驾驶证背面');
    if (provider.driverInfo.driverName == null) return ToastX.center('请输入真实姓名');
    if (provider.driverInfo.idNo == null) return ToastX.center('请输入身份证号');
    if (provider.driverInfo.dateTimeCertification == null)
      return ToastX.center('请选择驾驶证初领证日期');
    if (provider.driverInfo.termValidity == null)
      return ToastX.center('请选择驾驶证有效期');
    return DioUtils()
        .request(ReqMethod.POST, ServiceApi.submitDriverInformation, params: {
      'trueName': provider.driverInfo.driverName,
      'idNo': provider.driverInfo.idNo,
      'licenseDate': provider.driverInfo.dateTimeCertification,
      'validityTerm': provider.driverInfo.termValidity,
      'IDFront': provider.driverInfo.backIdCard, // 身份证国徽面（背面）
      'IDBack': provider.driverInfo.frontIdCard, // 身份证正面
      'licenseFront': provider.driverInfo.frontDriverLicense,
      'licenseBack': provider.driverInfo.backDriverLicense,
    }, success: (res) async {
      ToastX.center('提交成功');
      provider.setDriverInformation(
          idCardUploadState: true, driverMpdify: '0010');
      NavigatorUtil.goBack(context);
    });
  }

  /// 提交行驶证与车���������信息到后台
  static Future<void> submitDrivingLicense(BuildContext context) async {
    DriverInformation provider =
        Provider.of<DriverInformation>(context, listen: false);
    if (provider.driverInfo.frontDrivingLicense == null)
      return ToastX.center('请上传行驶证正面');
    if (provider.driverInfo.backDrivingLicense == null)
      return ToastX.center('请上传行驶证背面');
    if (provider.driverInfo.carImageList.length == 0)
      return ToastX.center('请上传车辆照片');
    if (provider.driverInfo.vehicleNumberPlate == null)
      return ToastX.center('请输入车辆牌号');
    if (provider.driverInfo.brandModels == null)
      return ToastX.center('请输入车辆品牌');
    return DioUtils()
        .request(ReqMethod.POST, ServiceApi.submitCarInformation, params: {
      'driverLicenseFront': provider.driverInfo.frontDrivingLicense, // 行驶证正面
      'driverLicenseBack': provider.driverInfo.backDrivingLicense, // 行驶证背面
      'CarNumber': provider.driverInfo.vehicleNumberPlate,
      'CarBrand': provider.driverInfo.brandModels,
      'CarImg': provider.driverInfo.carImageList,
    }, success: (res) async {
      ToastX.center('提交成功');
      provider.setDriverInformation(
          drivingUploadState: true, vehicleMpdify: '0010');
      Navigator.pop(context);
    });
  }

  /// 上传司机网约车驾驶证和车辆运营证
  static Future<void> submitQualificationCertificate(
      BuildContext context) async {
    DriverInformation provider =
        Provider.of<DriverInformation>(context, listen: false);
    if (provider.driverInfo.employment == null)
      return ToastX.center('请上传网约车驾驶证照片');
    if (provider.driverInfo.operate == null) return ToastX.center('请上传车辆运营证');
    return DioUtils().request(
        ReqMethod.POST, ServiceApi.submitQualificationCertificate,
        params: {
          'employment': provider.driverInfo.employment, // 网约车驾驶证照片
          'operate': provider.driverInfo.operate, // 车辆运行证
        }, success: (res) async {
      ToastX.center('提交成功');
      provider.setDriverInformation(
          qualificationCertificateState: true, qualificationMpdify: '0010');
      Navigator.pop(context);
    });
  }

  /// 获取余额
  static Future<String> getBalance() async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.driverGetBalance,
        params: {}, success: (res) async {
      return res['balance'];
    });
  }

  /// 获取全部余额
  static Future<String> getAllBalance() async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.getAllBalance,
        params: {}, success: (res) async {
      return res['balance'].toString();
    });
  }

  /// 获取余额(可用余额-不可提现)
  static Future<String> getFreezeBalance() async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.driverFetFreezeBalance, params: {},
            success: (res) async {
      return res['balance'];
    });
  }

  /// 用户账单查询 0 全部账单 1支出 2收入
  static Future<List> getBillInfo(
      String direction, int page, int pageSize) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.driverGetBillInfo,
        params: {"direction": direction, "page": page, "pageSize": pageSize},
        success: (res) async {
          var data=await EncryptData.decryptHttpData(res);
          return data;
    });
  }

  /// 银行卡绑定
  /// accountName 持卡人姓名
  /// accountNo 银行卡账号
  /// bankLeaveMobile 银行预留手机号手机号
  /// provinceName	 开户省名称
  /// cityName  开户市名称
  /// openBankName  开户行名称
  /// bankCode  开户行简称
  static Future<List> bindBankCard(
      BuildContext context,
      String accountName,
      String accountNo,
      String bankLeaveMobile,
//      String provinceName,
      String cityName,
      String openBankName,
      String bankCode) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.bindBankCard, params: {
      "accountName": accountName,
      "accountNo": accountNo,
      "bankLeaveMobile": bankLeaveMobile,
//      "provinceName": provinceName,
      "cityName": cityName,
      "openBankName": openBankName,
      "idNo": bankCode
    }, success: (res) async {
      ToastX.center('绑定成功');
      NavigatorUtil.goBack(context);
    }, failed: (ret) async {
      ToastX.center(ret.message);
    });
  }

  /// 获取银行卡绑定信息
  static Future getUserBankCard() async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.getUserBankCard,
        params: {}, success: (res) async {
          var data=await EncryptData.decryptHttpData(res);
          return data;
    });
  }

  /// 提现
  static Future withdrawals(BuildContext context, String amount) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.withdrawals,
        params: {"amount": amount}, success: (res) async {
      NavigatorUtil.jump(context, '/cashwithdrawalSubmission');
    }, failed: (res) async {
      var error = res.code;
      if (error == 9902 || error == 9901) {
        MyDialog.confirm('实名认证', "请完成实名认证", context, () {
          NavigatorUtil.jump(context, '/realNameAuthentication');
        });
      }
      return res;
    });
  }

  /// 获取开户银行
  static Future<List> getSupportBankList() async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.getSupportBankList, success: (res) async {
      List dataInfo = res;
      // GetSupportBankList data = GetSupportBankList.fromJson(res);
      return dataInfo;
    });
  }

  /// 获取司机路线 班次
  static Future<List> getTripRouteData() async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.getIntercityShift, params: {},
            success: (res) async {
      print(res);
      // if(res == null) return res;
      if (res == '') {
        return [];
      } else {
        return res;
      }
    });
  }

  /// 司机获取同行订单
  static Future getPeerOrdersByTimeTableID(String id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.getPeerOrdersByTimeTableID,
        params: {"departure_id": id}, success: (res) async {
      return res;
    });
  }

  /// 获取司机今日相关数据
  static Future<void> getDriverOperateInfo() async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.getDriverOperateInfo, params: {},
            success: (res) async {
      return res;
    });
  }

  /// 获取分享信息
  static Future<GetShareInfo> getShareInfo() async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getShareInfo,
      params: {'type': '0020'},
      success: (res) async {
        GetShareInfo shareData = GetShareInfo.fromJson(res);
        return shareData;
      },
    );
  }

  /// 司机认证费支付状态
  static Future getDriverFeeState() async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getDriverFeeState,
      params: {},
      success: (res) async {
        return res;
      },
    );
  }

  /// 车主认证提交审核
  static Future certificatonAudit(BuildContext context) async {
    PositionInformation dataInfo =
        Provider.of<PositionInformation>(context, listen: false);
    DriverInformation driverInfo =
        Provider.of<DriverInformation>(context, listen: false);
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.certificatonAudit, params: {
      'area': dataInfo.driverCurrentCity,
      'OperationModel': driverInfo.selectAccessionModeNum,
    }, success: (res) async {
      NavigatorUtil.jump(context, '/vehicleOwnerAudit');
    });
  }

  /// 司机��证��微��支��
  static Future<void> goToCheckOwner(BuildContext context, type) async {
    DriverInformation dataInfo =
        Provider.of<DriverInformation>(context, listen: false);
    PositionInformation dataLocation =
        Provider.of<PositionInformation>(context, listen: false);
    if (dataLocation.driverCurrentCity == '选择城市')
      return ToastX.center('请先选择城市');
    if (!dataInfo.driverInfo.idCardUploadState)
      return ToastX.center('请先去完善身份证与驾驶证信息');
    if (!dataInfo.driverInfo.drivingUploadState)
      return ToastX.center('请先去完善行驶证与车辆信息');
    if (type == '0010') {
      if (!dataInfo.driverInfo.qualificationCertificateState)
        return ToastX.center('请先去完善网约车驾驶证等信息');
    }
    return Request.certificatonAudit(context);
  }

  /// 司机认证费支付状态
  static void updateDriverName(BuildContext context, String userName) async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.updateDriverName,
      params: {'driver_name': userName},
      success: (res) async {
        ToastX.center('修改成功');
        NavigatorUtil.goBack(context);
      },
    );
  }

  /// 查询我的团队
  /// type  类型1-今天;2-昨天;3-七天以内
  static Future getMyPromotion(int page, int pageSize, String type) async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getMyPromotionAll,
      params: {
        'page': page,
        'pageSize': pageSize,
        'type': type,
      },
      success: (res) async {
        return res;
      },
    );
  }

  /// 关闭接单(收车)
  static void closeReceivingOrder(BuildContext context) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.endReceivingOrder,
        params: {}, success: (res) async {
      // SocketManage().driverCollection(context);
      Provider.of<DriverInformation>(context, listen: false)
          .setDriverInformation(workingStatus: '0030');
    });
  }

  /// 更新车辆信息
  /// String licensePlateNumber;  车牌信息
  /// String brand; 车辆品牌车型
  /// String certifyDateA = '1990-01-01'; 上牌时间
  /// String vehicleColor = '白色'; 车身颜色
  /// String address = '选择'; 城市
  /// String vin; 车辆识别码
  /// String engineid; 发动机号
  /// String distance; 行驶里程
  static void updataCarInfo(
      context,
      String _licensePlateNumber,
      String _brand,
      String _vehicleColor,
      String _vin,
      String _engineid,
      String _distance,
      String _certifyDate,
      String _address) {
    DioUtils().request(
      ReqMethod.POST,
      ServiceApi.updataCarInfo,
      params: {
        'vehicle_no': _licensePlateNumber,
        'brand': _brand,
        'certify_date_a': _certifyDate,
        'vehicle_color': _vehicleColor,
        'address': _address,
        'vin': _vin,
        'engineid': _engineid,
        'distance': _distance,
      },
      success: (res) async {
        // 设置车牌信息
        Provider.of<DriverInformation>(context, listen: false)
            .setDriverInformation(
                vehicleNumberPlate: _licensePlateNumber,
                brandModels: _brand,
                vehicleColor: _vehicleColor,
                vin: _vin,
                engineid: _engineid,
                distance: _distance,
                certifyDate: _certifyDate,
                carAddress: _address);
        ToastX.center('提交成功');
        NavigatorUtil.goBack(context);
      },
    );
  }

  /// 去接乘客
  static Future<bool> goToPage({String passengerId, String orderId}) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.confirmReceipt, params: {
      'passenger_id': passengerId, // 乘客ID
      'order_id': orderId, // 订单ID
    }, success: (res) async {
      return true;
    });
  }

  /// 查询订单是否支付成功
  /// 0000:已支付 其他:未支付   type order 快车 ,intercity 城际 ,free 顺风车
  static Future<String> getPayStateFun(String orderId, String type) async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getPayState,
      params: {'order_id': orderId, 'type': type},
      success: (res) async {
        GetPayState _dataInfo = GetPayState.fromJson(res);
        return _dataInfo.payState;
      },
      failed: (res) async {
        ErrorEntity _dataInfo = res;
        return _dataInfo.code.toString();
      },
    );
  }

  /// 司机获取行程中订单
  static Future<GetTripOrderInfo> getOnTripOrderByDriverId() async {
    return await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getOnTripOrderByDriverId,
      params: {},
      success: (res) async {
        if (res.length != 0) {
          return await DioUtils().request(
            ReqMethod.POST,
            ServiceApi.getTripOrderInfo,
            params: {
              'order_id': res['id'],
            },
            success: (val) async {
              var getTripOrderInfo = GetTripOrderInfo.fromJson(val);
              return getTripOrderInfo;
            },
          );
        } else {
          return GetTripOrderInfo();
        }
      },
    );
  }

  /// 获取行程订单信息
  static void getOrderInfo({BuildContext context, String orderId}) async {
    await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.getTripOrderInfo,
      params: {
        'order_id': orderId,
      },
      success: (val) async {
        var getTripOrderInfo = GetTripOrderInfo.fromJson(val);
        print('获取行程订单信息');
        print(getTripOrderInfo.depAre);
        Provider.of<OrderInformation>(context, listen: false).setOrderInfo(
          orderId: orderId,
          status: getTripOrderInfo.status,
          depAre: getTripOrderInfo.depAre,
          depLatitude: getTripOrderInfo.depLatitude,
          depLongitude: getTripOrderInfo.depLongitude,
          destArea: getTripOrderInfo.destArea,
          destLatitude: getTripOrderInfo.destLatitude,
          destLongitude: getTripOrderInfo.destLongitude,
          passengerHeadimgurl: getTripOrderInfo.passengerHeadimgurl,
          passengerMobile: getTripOrderInfo.passengerMobile,
          lastNum: getTripOrderInfo.lastNum,
        );
        print(getTripOrderInfo.driverName);
      },
    );
  }

  /// 到达乘客约定地点
  static void driverArriveBoardingPointFun(
      {BuildContext context, String orderId}) async {
    print(orderId);
    await DioUtils()
        .request(ReqMethod.POST, ServiceApi.driverArriveBoardingPoint, params: {
      'order_id': orderId,
    }, success: (res) async {
      Provider.of<OrderInformation>(context, listen: false)
          .setOrderInfo(status: '0015');
      Provider.of<OrderInformation>(context, listen: false)
          .setOrderInfo(intercityStatus: '0055');
    });
  }

  /// 接到乘客出发
  static void receivePassengerFun(
      {BuildContext context, String orderId, Future success}) async {
    await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.receivePassenger,
      params: {
        'order_id': orderId,
      },
      success: (res) async {
        Provider.of<OrderInformation>(context, listen: false)
            .setOrderInfo(status: '0020');
        // NavigatorUtil.jump(context, '/pickUpPassengers');
      },
    );
  }

  /// 到达目的地
  static void orderTripEndFun({BuildContext context, String orderId}) async {
    await DioUtils().request(
      ReqMethod.POST,
      ServiceApi.orderTripEnd,
      params: {
        'order_id': orderId,
        'dest_longitude':
            Provider.of<PositionInformation>(context, listen: false)
                .driverLocation
                .longitude,
        'dest_latitude':
            Provider.of<PositionInformation>(context, listen: false)
                .driverLocation
                .latitude,
        'dest_area': Provider.of<PositionInformation>(context, listen: false)
            .locationName,
      },
      success: (res) async {
        NavigatorUtil.jump(context,
            "/confirmedAmount?orderId=$orderId&sumCost=${res['cost']['sum_cost']}&startCost=${res['cost']['start_cost']}&timeCost=${res['cost']['time_cost']}&distanceCost=${res['cost']['distance_cost']}");
      },
    );
  }

  /// 到达目的地
  static void driverCancelOrderFun(
      {BuildContext context, String orderId, String cancellationReason}) async {
    await DioUtils()
        .request(ReqMethod.POST, ServiceApi.driverCancelOrder, params: {
      'order_id': orderId,
      'reason': cancellationReason,
    }, success: (res) async {
      NavigatorUtil.jump(context, '/successfulCancellationOrder');
    });
  }

  /// 发起收款
  static void orderInitiateCollectionFun(
      {BuildContext context,
      String orderId,
      String roadToll,
      String sumCost,
      String parkingRate}) async {
    await DioUtils()
        .request(ReqMethod.POST, ServiceApi.orderInitiateCollection, params: {
      'order_id': orderId,
      'toll_fee': roadToll, // 过路费
      'parking_fee': sumCost, // 停车费
    }, success: (res) async {
      DioUtils().request(ReqMethod.POST, ServiceApi.getVerification, params: {},
          success: (res01) async {
        print('qqqqqqqq------${res01.toString()}');
        if (res01['isVerification'] == 1) {
          Provider.of<DriverInformation>(context, listen: false)
              .setNeedNewFace('1');
          DioUtils().request(ReqMethod.POST, ServiceApi.endReceivingOrder,
              params: {}, success: (res) async {
            Provider.of<DriverInformation>(context, listen: false)
                .setDriverInformation(workingStatus: '0030');
          });
        } else {
          Provider.of<DriverInformation>(context, listen: false)
              .setNeedNewFace('0');
        }
        double moneyData = double.parse(sumCost) +
            double.parse(roadToll) +
            double.parse(parkingRate);
        //将订单id值为null mqtt 30秒定位使用
        Provider.of<OrderInformation>(context, listen: false).setNullOrderid();
        NavigatorUtil.jump(context, '/endTrip?money=${moneyData.toString()}');
      });
    });
  }

  /// 司机获取乘客顺风车详情
  static Future getUserRideOrderInfoFun(String id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.getUserRideOrderInfo,
        params: {'ride_id': id}, success: (res) async {
      return res;
    });
  }

  /// 捎上乘客
  static void driverArriveBoardingPoint(
      {String cId,
      String sjId,
      bool gogoBack = false,
      BuildContext context}) async {
    return showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: Text("确认要捎上该乘客？"),
        actions: <Widget>[
          FlatButton(
            child: Text("取消"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          FlatButton(
            child: Text("确认"),
            onPressed: () async {
              Navigator.of(context).pop();
              await DioUtils().request(
                ReqMethod.POST,
                ServiceApi.confirmFreeRideOrder,
                params: {'ride_id': cId, 'driver_order_id': sjId},
                success: (res) async {
                  if (gogoBack) {
                    print('gogoBack=======true');
                    eventBus.fire(new RefreshCarpoolPassengers(1));
                    Navigator.of(context)..pop()..pop();
                  } else {
                    print('gogoBack=======false');
                    NavigatorUtil.jump(
                        context, '/carpoolFellowPassengers?id=$sjId');
                  }
                  ToastX.center("顺风车订单成立");
                },
              );
            },
          ),
        ],
      ),
    );
  }

  /// 获取订单信息
  static Future driverGetIntercityOrder(
      String _intercityId, BuildContext context) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.driverGetIntercityOrder,
        params: {'order_id': _intercityId}, success: (res) async {
      Provider.of<OrderInformation>(context, listen: false).setOrderInfo(
        orderId: res['id'],
        intercityStatus: res['intercity_status'],
        passengerName: res['passenger_name'],
        depLongitude: res['dep_longitude'],
        depLatitude: res['dep_latitude'],
        depAre: res['dep_are'],
        destLongitude: res['dest_longitude'],
        destLatitude: res['dest_latitude'],
        destArea: res['dest_area'],
        passengerMobile: res['passenger_mobile'],
        passengerHeadimgurl: res['passenger_headimgurl'],
        lastNum: res['last_num'],
        peopleNumber: res['people_number'],
        depTime: res['dep_time'],
      );
      return res;
    });
  }

  /// 司机去接乘客
  static void pickUpPassengers(context, _intercityId) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.pickUpPassengers,
        params: {'order_id': _intercityId}, success: (res) async {
      Provider.of<OrderInformation>(context, listen: false)
          .setOrderInfo(status: '0015');
      Provider.of<OrderInformation>(context, listen: false)
          .setOrderInfo(intercityStatus: '0055');
    });
  }

  /// 乘机出行接到乘客
  static void rintercityEceivePassenger(context, _orderId) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.receivePassenger,
        params: {'order_id': _orderId}, success: (res) async {
      Navigator.pop(context);
      // Navigator.of(context).popUntil((route) => route.isFirst);
    });
  }

  /// 乘机出行到达目的地
  static void orderTripEndIntercity(
      {BuildContext context, String orderId}) async {
    await DioUtils()
        .request(ReqMethod.POST, ServiceApi.tripArriveDestination, params: {
      'order_id': orderId,
      'dest_longitude': Provider.of<PositionInformation>(context, listen: false)
          .driverLocation
          .longitude,
      'dest_latitude': Provider.of<PositionInformation>(context, listen: false)
          .driverLocation
          .latitude,
      'dest_area':
          Provider.of<PositionInformation>(context, listen: false).locationName,
    }, success: (res) async {
      Navigator.pop(context);
      // Navigator.of(context).popUntil((route) => route.isFirst);
    });
  }

  /// 获取行程订单列表 分为历史行程订单和行程中订单
  static Future getItineraryOrder({String page, String type}) async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.getTripOrderList,
        params: {'page': page, 'pageSize': '20', 'type': type},
        success: (res) async {
          var data= await EncryptData.decryptHttpData(res);
          return data;
    });
  }

  /// 获取行程订单列表 分为历史行程订单和行程中订单
  static Future driverOrderHistory({String page}) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.driverOrderHistory, params: {
      'page': page,
      'pageSize': '20',
    }, success: (res) async {
      return res;
    });
  }

  /// 获取司机信息修改状���
  static Future getDriverModifyStatus(BuildContext context) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.getDriverModifyStatus,
        params: {}, success: (res) {
      Provider.of<DriverInformation>(context, listen: false)
          .setDriverInformation(
              driverMpdify: res['driver_mpdify'],
              vehicleMpdify: res['vehicle_mpdify'],
              qualificationMpdify: res['qualification_mpdify']);
    });
  }

  /// 获取扫码收款小程序二维码
  static Future getSmallProgramCode(
      {String routeId, String timeId, String driverId}) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.getWxShareQrcode, params: {
      'route_id': routeId,
      'time_id': timeId,
      'driver_id': driverId,
    }, success: (res) async {
      return res;
    });
  }

  /// 七牛genUptoken
  static Future genUptoken({String clientId, String defaultFix}) async {
    return await QiniuDioUtils().request(
        ReqMethod.POST, 'http://test.auth.maitianshanglv.com/qiniu/uptoken/gen',
        params: {
          'client_id': clientId,
          'default_fix': defaultFix,
          'bucket_name': 'maitianshanglv',
        }, success: (res) async {
      return res;
    });
  }

  /// 七牛上传
  static Future qiniuUpload(
      {String key, String uploadToken, String file}) async {
    return await QiniuDioUtils()
        .uploadFile(ReqMethod.POST, 'http://upload.qiniup.com/', params: {
      'file': file,
      'key': key,
      'token': uploadToken,
    }, success: (res) async {
      return res;
    });
  }

  /// 顺风车通联扫码
  static Future payAllin(
      {String orderId,
      String businessCode,
      String payType,
      String authcode,
      String allinPaytype}) async {
    await DioUtils().request(ReqMethod.POST, ServiceApi.payAllin, params: {
      "id": orderId,
      "business_code": businessCode,
      "pay_type": payType,
      "authcode": authcode,
      "allin_paytype": allinPaytype
    }, success: (res) {
      print(res);
    });
  }

  /// 接送机扫码
  static Future pickPayAllin(
      {String orderId,
      String businessCode,
      String payType,
      String authcode,
      String allinPaytype}) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.payAllin, params: {
      "id": orderId,
      "business_code": businessCode,
      "pay_type": payType,
      "authcode": authcode,
      "allin_paytype": allinPaytype
    }, success: (res) {
      return res;
    });
  }

  /// 司机出车扫脸
  static Future getFaceRecognitionState() async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.getFaceRecognitionState, params: {},
            success: (res) {
      return res;
    });
  }

  /// 获取接送机数据
  static Future getPickupdata(BuildContext context, int page) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.driverOrderList, params: {
      'page': page.toString(),
    }, success: (res) {
      print('qqqqqqqqqqqqqqqq--------${res.toString()}');
      return res;
    });
  }

  /// 获取接送机数据
  static Future getTripByBooking(BuildContext context, String bookingid) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.getTripByBooking, params: {
      'booking_id': bookingid,
    }, success: (res) {
      return res;
    });
  }

  /// 账号注销
  static void logOffUser(BuildContext context) async {
    var state = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('注销当前账号？'),
        actions: <Widget>[
          FlatButton(
            child: Text('暂不'),
            onPressed: () => Navigator.pop(context, false),
          ),
          FlatButton(
            child: Text('注销'),
            onPressed: () => Navigator.pop(context, true),
          ),
        ],
      ),
    );
    if (state) {
      await DioUtils().request(ReqMethod.POST, ServiceApi.getLogOffUser,
          params: {}, success: (res) async {
        ToastX.center("账号已注销");
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString(AppStorageInterface.LOGINTOKEN, ''); // 存储token到本地
        MqttManage.getInstance().disconnect();
        NavigatorUtil.goToLoginRemovePage();
      });
    }
  }

  /// 公安接口
  static Future submitFaceRecognition(
      String image, String cardNum, String name, String random) async {
    return await DioUtils()
        .request(ReqMethod.POST, ServiceApi.submitFaceRecognition, params: {
      'image': image,
      'image_type': 'BASE64',
      'id_card_number': cardNum,
      'name': name,
      'random': random,
    }, success: (res) {
      return res;
    });
  }

  /// 公安接口
  static Future uploadAuthenticationRecords(String state) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.uploadAuthenticationRecords,
        params: {
          'state': state,
          'type': '0010',
        }, success: (res) {
      return res;
    });
  }

  ///接送机确认乘客到达
  static Future pickupEnterPassengerArrives(String id) async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.pickUpEnterArrved, params: {"id": id},
        success: (res) {
      return 'success';
    });
  }

  /// 获取动态广告图
  static Future<AdvertPicture> advertPicture() async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.getFrontImage,
        params: {"type": "driver"}, success: (res) async {
      AdvertPicture _data = AdvertPicture.fromJson(res);
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString(AppStorageInterface.ADVERTPICTUREIMG, _data.fullImgUrl);
      return _data;
    });
  }

  ///查询是否录音
  static Future queryRecordStatus() async {
    return await DioUtils().request(
        ReqMethod.POST, ServiceApi.queryRecordStatus, success: (res) async {
      return res;
    });
  }

  ///上传录音url
  static Future submitRecordUrl(String url, String orderId, String time) async {
    return await DioUtils().request(ReqMethod.POST, ServiceApi.submitRecordUrl,
        params: {"url": url, "order_id": orderId, "time_stamp": time},
        success: (res) {
      return res;
    });
  }
}
